import React, { useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useUserStore } from '@/stores';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';

export const LoginPage: React.FC = () => {
  const { login, isAuthenticated, isLoading, error } = useUserStore();
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  });

  if (isAuthenticated) {
    return <Navigate to="/" replace />;
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await login(formData);
    } catch (error) {
      // 错误已在store中处理
    }
  };

  const handleChange = (field: string) => (value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            登录到色彩搭配应用
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            还没有账户？{' '}
            <a href="/register" className="font-medium text-blue-600 hover:text-blue-500">
              立即注册
            </a>
          </p>
        </div>
        
        <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
          <div className="space-y-4">
            <Input
              label="用户名"
              type="text"
              value={formData.username}
              onChange={handleChange('username')}
              placeholder="请输入用户名"
              required
            />
            
            <Input
              label="密码"
              type="password"
              value={formData.password}
              onChange={handleChange('password')}
              placeholder="请输入密码"
              required
            />
          </div>

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-md p-4">
              <p className="text-red-800 text-sm">{error}</p>
            </div>
          )}

          <div>
            <Button
              type="submit"
              className="w-full"
              disabled={isLoading || !formData.username || !formData.password}
              loading={isLoading}
            >
              登录
            </Button>
          </div>

          <div className="text-center">
            <a href="/" className="text-sm text-gray-600 hover:text-gray-900">
              返回首页
            </a>
          </div>
        </form>
      </div>
    </div>
  );
};